package com.poker.service;

import com.poker.entity.ProductOrder;
import com.poker.repository.ProductOrderRepository;
import com.poker.util.Misc;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ProductOrderService
 * @Description TODO
 * @Author duyuanyuan
 * @Date 2019/3/13 13:27
 * @Version 1.0
 **/
@Service
public class ProductOrderService {

    @Resource
    private ProductOrderRepository repository;

    /**
     * @param: [page, size];
     * @return: org.springframework.data.domain.Page<Product>;
     * @Description: 不带条件分页查询;
     */
    public Page<ProductOrder> findAllProduct(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        return repository.findAll(pageable);
    }

    /**
     * @param: [page, size, workOrder];
     * @return: org.springframework.data.domain.Page<WorkOrder>;
     * @Description: 带条件的分页查询;
     */
    public Page<ProductOrder> queryProductOrder(Integer page, Integer size, ProductOrder productOrder) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");

        return repository.findAll((Specification<ProductOrder>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            if (Misc.isNotEmpty(productOrder.getOrderNumber()))
                list.add(criteriaBuilder.equal(root.get("OrderNumber").as(String.class), productOrder.getOrderNumber()));


            Predicate[] predicateArray = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(predicateArray));
        }, pageable);
    }

    public ProductOrder getById(String id) {
        return repository.getOne(id);
    }

}
